<template>
  <el-container style="height: 80vh; border: 1px solid #eee; overflow: hidden">
    <el-main>
      <div class="user">
        <div class="hm-search">
          <el-breadcrumb separator-class="el-icon-arrow-right">
            <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item>商品管理</el-breadcrumb-item>
            <el-breadcrumb-item>商品列表</el-breadcrumb-item>
          </el-breadcrumb>
        </div>
        <el-steps :active="activeIndex - 0" align-center>
          <el-step title="基本信息"></el-step>
          <el-step title="商品参数"></el-step>
          <el-step title="商品属性"></el-step>
          <el-step title="商品图片"></el-step>
          <el-step title="商品内容"></el-step>
        </el-steps>
        <el-form
          :model="goodData"
          status-icon
          label-width="120px"
          :label-position="labelPosition"
          :rules="rulesFrom"
          ref="addFormRef"
        >
          <el-tabs
            :tab-position="tabPosition"
            v-model="activeIndex"
            @tab-click="tabClickFn"
            :before-leave="beforeTabLeave"
          >
            <el-tab-pane label="基本信息" name="0">
              <el-form-item label="商品名称" prop="goods_name">
                <el-input
                  v-model="goodData.goods_name"
                  autocomplete="off"
                ></el-input>
              </el-form-item>
              <el-form-item label="商品价格" prop="goods_price" type="number">
                <el-input
                  v-model="goodData.goods_price"
                  autocomplete="off"
                ></el-input>
              </el-form-item>
              <el-form-item label="商品重量" prop="goods_weight">
                <el-input
                  v-model="goodData.goods_weight"
                  autocomplete="off"
                ></el-input>
              </el-form-item>
              <el-form-item label="商品数量" prop="goods_number">
                <el-input
                  v-model="goodData.goods_number"
                  autocomplete="off"
                ></el-input>
              </el-form-item>
              <el-form-item label="商品分类">
                <el-cascader
                  expandTrigger="hover"
                  v-model="goodData.goods_cat"
                  :options="cascader.cascaderData"
                  :show-all-levels="false"
                  :props="defaultCate"
                  @change="cateChanged"
                  clearable
                ></el-cascader>
              </el-form-item>
            </el-tab-pane>
            <el-tab-pane label="商品参数" name="1">
              <div v-for="item in cascader.manyData" :key="item.attr_id">
                <p>{{ item.attr_name }}</p>
                <el-checkbox-group v-model="item.attr_vals">
                  <el-checkbox
                    v-for="(_item, index) in item.attr_vals"
                    :key="index"
                    :label="_item"
                    border
                  ></el-checkbox>
                </el-checkbox-group>
              </div>
            </el-tab-pane>
            <el-tab-pane label="商品属性" name="2">
              <el-form-item
                v-for="item in cascader.onlyData"
                :key="item.attr_id"
                :label="item.attr_name"
              >
                <el-input
                  v-model="item.attr_vals"
                  autocomplete="off"
                ></el-input>
              </el-form-item>
            </el-tab-pane>
            <el-tab-pane label="商品图片" name="3">
              <el-upload
                :on-preview="previewFn"
                :action="cascader.addUpload"
                :headers="headersObj"
                list-type="picture"
                :on-success="successFn"
                :on-remove="removeFn"
              >
                <el-button size="small" type="primary">点击上传</el-button>
                <template>
                  <div class="el-upload__tip">
                    只能上传jpg/png文件，且不超过500kb
                  </div>
                </template>
              </el-upload>
            </el-tab-pane>
            <el-tab-pane label="商品内容" name="4">
              <el-input
                v-model="goodData.goods_introduce"
                :autosize="{ minRows: 2, maxRows: 4 }"
                type="textarea"
                placeholder="Please input"
              >
              </el-input>
              <el-button type="primary" @click="addGoodsFn" class="btnAdd"
                >添加商品</el-button
              >
            </el-tab-pane>
          </el-tabs>
        </el-form>
      </div>
    </el-main>
    <el-dialog title="图片预览" v-model="cascader.previewVisible" width="50%">
      <img width="400px" :src="cascader.picUrl" alt="" />
    </el-dialog>
  </el-container>
</template>
<script>
import _ from "lodash";
import { onMounted, reactive, ref, getCurrentInstance } from "vue";
import { getCate, getParams, addGoods } from "../../http/api";
import { addUpload } from "../../http/index";
import { useStore } from "vuex";
import { useRouter } from "vue-router";
export default {
  setup() {
    const { proxy } = getCurrentInstance();
    const router = useRouter();
    const store = useStore();
    let activeIndex = ref("0");
    const tabPosition = ref("left");
    const labelPosition = ref("top");
    const goodData = reactive({
      goods_name: "",
      goods_cat: [],
      goods_price: 0,
      goods_number: 0,
      goods_weight: 0,
      pics: [],
      goods_introduce: "",
      attrs: [],
    });
    const rulesFrom = reactive({
      goods_name: [
        { required: true, message: "请输入商品名称", trigger: "blur" },
      ],
      goods_price: [
        { required: true, message: "请输入商品价格", trigger: "blur" },
      ],
      goods_weight: [
        { required: true, message: "请输入商品重量", trigger: "blur" },
      ],
      goods_number: [
        { required: true, message: "请输入商品数量", trigger: "blur" },
      ],
    });
    const cascader = reactive({
      cascaderData: [],
      manyData: [],
      onlyData: [],
      addUpload: addUpload,
      previewVisible: false,
      picUrl: "",
    });
    const headersObj = reactive({
      Authorization: store.state.token,
    });
    const getCateFn = async () => {
      const res = await getCate({ type: 3 });
      // console.log("111",res);
      cascader.cascaderData = res;
    };
    //级联选择框选中项变化，会触发这个函数
    const cateChanged = () => {
      if (goodData.goods_cat.length !== 3) {
        goodData.goods_cat = [];
        console.log(1);
        return;
      }
    };
    //阻止标签切换(切换标签之前执行)
    const beforeTabLeave = (active, oldactive) => {
      // console.log("111",active, oldactive);
      if (oldactive == "0" && goodData.goods_cat.length !== 3) {
        proxy.$message.error("请先选择商品分类三级");
        return false;
      }
    };
    // tab改变时执行 点击商品分类 获取动态参数
    const tabClickFn = async () => {
      // console.log("@@@@@@ ");
      if (activeIndex.value == "1") {
        const id = goodData.goods_cat[goodData.goods_cat.length - 1];
        const res = await getParams(id, { sel: "many" });
        res.map((item) => {
          item.attr_vals =
            item.attr_vals.length == 0 ? [] : item.attr_vals.split(",");
          return item;
        });
        cascader.manyData = res;
        console.log("####", res);
      } else if (activeIndex.value == "2") {
        const id = goodData.goods_cat[goodData.goods_cat.length - 1];
        const res = await getParams(id, { sel: "only" });
        console.log("only", res);
        cascader.onlyData = res;
      }
    };
    //图片上传成功以后执行的方法
    const successFn = (res, file, fileList) => {
      console.log("pic", res, file, fileList);
      goodData.pics.push({ pic: file.response.data.tmp_path });
      // console.log("goodData",goodData)
    };
    //删除图片以后执行的方法
    const removeFn = (file, fileList) => {
      // console.log("file", file,fileList);
      goodData.pics = fileList;
    };
    //点击已经上传的图片  图片预览
    const previewFn = (file) => {
      console.log("%%%%%%%", file.response.data.url);
      const tmUrl = file.response.data.url.replace(
        "localhost:",
        "localhost:8889"
      );
      cascader.picUrl = tmUrl;
      // console.log(cascader.picUrl);
      cascader.previewVisible = true;
    };
    //点击添加商品
    const addGoodsFn = () => {
      proxy.$refs.addFormRef.validate(async (valid) => {
        if (!valid) {
          return proxy.$message.error("请填写必要项");
        }
        //处理动态参数
        cascader.manyData.forEach((item) => {
          const attrObj = {
            attr_id: item.attr_id,
            attr_value: item.attr_vals.join(","),
          };
          goodData.attrs.push(attrObj);
          //  console.log(attrObj)
        });
        //处理静态属性
        cascader.onlyData.forEach((item) => {
          goodData.attrs.push({
            attr_id: item.attr_id,
            attr_value: item.attr_vals,
          });
        });
        //处理goods_cat
        var from = _.cloneDeep(goodData);
        // console.log("from",from)
        from.goods_cat = from.goods_cat.join(",");
        // console.log("%%%%", goodData);

        await addGoods(from);
        console.log("@@@@", from);
        router.replace({
          name: "Goods",
        });
      });
    };
    const defaultCate = reactive({
      label: "cat_name",
      children: "children",
      value: "cat_id",
    });
    onMounted(() => {
      getCateFn();
    });
    return {
      activeIndex,
      tabPosition,
      labelPosition,
      goodData,
      cascader,
      getCateFn,
      rulesFrom,
      defaultCate,
      cateChanged,
      beforeTabLeave,
      tabClickFn,
      headersObj,
      successFn,
      removeFn,
      previewFn,
      addGoodsFn,
    };
  },
};
</script>
<style scoped lang="scss">
.hm-search {
  height: 70px;
}
.el-main {
  background-color: #eee;
}
.user {
  background-color: #fff;
  padding: 15px;
}
::v-deep .el-dialog__body {
  img {
    width: 400px;
    height: 300px;
  }
  width: 100%;
  height: 300px;
}
</style>